import React, { useState, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { 
  Table, 
  Card, 
  Button, 
  Tag, 
  Space, 
  Row, 
  Col, 
  Statistic, 
  Progress, 
  Avatar, 
  Tooltip, 
  Modal, 
  List, 
  Typography,
  Badge,
  Divider,
  Descriptions,
  Input,
  Select,
  DatePicker,
  Tabs,
  Alert,
  message,
  Popconfirm,
  Rate,
  Dropdown,
  Menu,
  Form,
  Switch,
  InputNumber
} from "antd";
import { 
  PlusOutlined, 
  EyeOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  MoreOutlined,
  TeamOutlined,
  BookOutlined,
  UserOutlined,
  ClockCircleOutlined,
  EnvironmentOutlined,
  CheckCircleOutlined,
  SearchOutlined,
  FilterOutlined,
  ExportOutlined,
  ImportOutlined,
  SettingOutlined,
  StarOutlined,
  TrophyOutlined,
  BarChartOutlined,
  ReloadOutlined,
  FileTextOutlined,
  ExperimentOutlined
} from "@ant-design/icons";
import { COURSES, CLASSES, generateStudents } from "../../../utils/mockData";

const { Text, Title } = Typography;
const { TextArea } = Input;
const { Option } = Select;

interface Student {
  id: string;
  name: string;
  studentId: string;
  avatar?: string;
  major: string;
  grade: string;
  joinTime: string;
  status: "active" | "inactive";
  attendance: number;
  score: number;
}

interface Class {
  id: string;
  name: string;
  courseId: string;
  students: Student[];
  schedule: string;
  location: string;
  capacity: number;
  enrolled: number;
  status: "active" | "ended" | "upcoming";
}

interface Course {
  id: string;
  name: string;
  code: string;
  credit: number;
  semester: string;
  description: string;
  totalStudents: number;
  totalClasses: number;
  status: "进行中" | "未开始" | "已结束";
  teacher: string;
  classes: Class[];
  schedule: string;
  location: string;
  rating: number;
  difficulty: "简单" | "中等" | "困难";
  category: "必修" | "选修" | "实验";
  createTime: string;
  updateTime: string;
  tags: string[];
  isPopular: boolean;
  completionRate: number;
  averageScore: number;
}

const TeacherCourses: React.FC = () => {
  const navigate = useNavigate();
  const [selectedCourse, setSelectedCourse] = useState<Course | null>(null);
  const [courseDetailVisible, setCourseDetailVisible] = useState(false);
  const [classDetailVisible, setClassDetailVisible] = useState(false);
  const [selectedClass, setSelectedClass] = useState<Class | null>(null);
  const [searchText, setSearchText] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [difficultyFilter, setDifficultyFilter] = useState<string>("all");
  const [categoryFilter, setCategoryFilter] = useState<string>("all");
  const [showAdvancedSearch, setShowAdvancedSearch] = useState(false);
  const [selectedTab, setSelectedTab] = useState("courses");
  const [createTimeFilter, setCreateTimeFilter] = useState<string>("");
  const [ratingFilter, setRatingFilter] = useState<string>("");
  const [completionRateFilter, setCompletionRateFilter] = useState<string>("");
  
  // 学生信息管理状态
  const [selectedCourseForStudents, setSelectedCourseForStudents] = useState<Course | null>(null);
  const [studentSearchText, setStudentSearchText] = useState("");
  const [studentStatusFilter, setStudentStatusFilter] = useState<string>("all");
  const [studentMajorFilter, setStudentMajorFilter] = useState<string>("all");
  const [addStudentModalVisible, setAddStudentModalVisible] = useState(false);
  const [newStudentData, setNewStudentData] = useState({
    name: "",
    studentId: "",
    major: "",
    grade: "",
    email: ""
  });

  // 发布作业相关状态
  const [publishHomeworkModalVisible, setPublishHomeworkModalVisible] = useState(false);
  const [selectedCourseForHomework, setSelectedCourseForHomework] = useState<Course | null>(null);
  const [homeworkForm] = Form.useForm();

  // 使用统一的学生数据生成函数
  const generateStudentsForCourse = (count: number, major: string, grade: string, startIndex: number = 0): Student[] => {
    const students = generateStudents(count, major, grade, startIndex);
    return students.map((student, index) => ({
      id: student.id,
      name: student.name,
      studentId: student.studentNumber,
      avatar: student.avatar,
      major: student.major,
      grade: student.grade,
      joinTime: student.enrollTime,
      status: student.status,
      attendance: Math.floor(Math.random() * 20) + 80, // 80-100%
      score: Math.floor(Math.random() * 30) + 70, // 70-100
    }));
  };

  // 使用统一的课程数据
  const mockCourses: Course[] = useMemo(() => {
    let studentIndex = 0;
    
    return COURSES.map(course => {
      // 获取该课程关联的班级
      const courseClasses = CLASSES.filter(cls => course.classIds.includes(cls.id));
      
      // 生成班级数据
      const classes: Class[] = courseClasses.map(cls => {
        const students = generateStudentsForCourse(cls.studentCount, cls.major, cls.grade, studentIndex);
        studentIndex += cls.studentCount;
        
        return {
          id: cls.id,
          name: cls.name,
          courseId: course.id,
          students,
          schedule: course.schedule,
          location: course.location,
          capacity: cls.maxStudents,
          enrolled: cls.studentCount,
          status: "active" as const
        };
      });
      
      return {
        id: course.id,
        name: course.name,
        code: course.code,
        credit: course.credits,
        semester: course.semester,
        description: course.description,
        totalStudents: course.currentStudents,
        totalClasses: courseClasses.length,
        status: "进行中" as const,
        teacher: course.teacher.name,
        schedule: course.schedule,
        location: course.location,
        rating: 4.2 + Math.random() * 0.6, // 4.2-4.8
        difficulty: "中等" as const,
        category: "必修" as const,
        createTime: course.createTime,
        updateTime: course.createTime,
        tags: ["计算机", "编程"],
        isPopular: Math.random() > 0.5,
        completionRate: 85 + Math.floor(Math.random() * 15), // 85-99%
        averageScore: 80 + Math.floor(Math.random() * 15), // 80-95
        classes
      };
    });
  }, []);

  // 筛选后的课程数据
  const filteredCourses = useMemo(() => {
    return mockCourses.filter(course => {
      const matchesSearch = course.name.toLowerCase().includes(searchText.toLowerCase()) ||
                           course.code.toLowerCase().includes(searchText.toLowerCase()) ||
                           course.description.toLowerCase().includes(searchText.toLowerCase());
      
      const matchesStatus = statusFilter === "all" || course.status === statusFilter;
      const matchesDifficulty = difficultyFilter === "all" || course.difficulty === difficultyFilter;
      const matchesCategory = categoryFilter === "all" || course.category === categoryFilter;
      
      // 高级筛选条件
      const matchesCreateTime = !createTimeFilter || course.createTime.includes(createTimeFilter);
      
      let matchesRating = true;
      if (ratingFilter) {
        const [min, max] = ratingFilter.split('-').map(Number);
        matchesRating = course.rating >= min && course.rating <= max;
      }
      
      let matchesCompletionRate = true;
      if (completionRateFilter) {
        const [min, max] = completionRateFilter.split('-').map(Number);
        matchesCompletionRate = course.completionRate >= min && course.completionRate <= max;
      }
      
      return matchesSearch && matchesStatus && matchesDifficulty && matchesCategory && 
             matchesCreateTime && matchesRating && matchesCompletionRate;
    });
  }, [mockCourses, searchText, statusFilter, difficultyFilter, categoryFilter, 
      createTimeFilter, ratingFilter, completionRateFilter]);

  // 统计数据
  const stats = {
    totalCourses: mockCourses.length,
    totalStudents: mockCourses.reduce((sum, course) => sum + course.totalStudents, 0),
    totalClasses: mockCourses.reduce((sum, course) => sum + course.totalClasses, 0),
    activeCourses: mockCourses.filter(course => course.status === "进行中").length,
    popularCourses: mockCourses.filter(course => course.isPopular).length,
    averageRating: mockCourses.reduce((sum, course) => sum + course.rating, 0) / mockCourses.length,
  };

  const columns = [
    {
      title: "课程信息",
      key: "courseInfo",
      render: (record: Course) => (
        <div>
          <div style={{ fontWeight: 'bold', fontSize: '16px' }}>
            {record.name}
            {record.isPopular && <StarOutlined style={{ color: '#faad14', marginLeft: 8 }} />}
          </div>
          <div style={{ color: '#666', fontSize: '12px' }}>
            {record.code} · {record.semester} · {record.credit}学分
          </div>
          <div style={{ color: '#999', fontSize: '12px' }}>{record.description}</div>
          <div style={{ marginTop: 4 }}>
            {record.tags.map(tag => (
              <Tag key={tag} style={{ marginRight: 4, marginBottom: 2, fontSize: '11px' }}>
                {tag}
              </Tag>
            ))}
          </div>
        </div>
      ),
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: string) => (
        <Tag color={status === "进行中" ? "green" : status === "未开始" ? "blue" : "default"}>
          {status}
        </Tag>
      ),
    },
    {
      title: "难度",
      dataIndex: "difficulty",
      key: "difficulty",
      render: (difficulty: string) => (
        <Tag color={difficulty === "简单" ? "green" : difficulty === "中等" ? "orange" : "red"}>
          {difficulty}
        </Tag>
      ),
    },
    {
      title: "评价",
      key: "rating",
      render: (record: Course) => (
        <div>
          <Rate disabled defaultValue={record.rating} style={{ fontSize: '12px' }} />
          <div style={{ fontSize: '11px', color: '#666', marginTop: 2 }}>
            {record.rating.toFixed(1)}分
          </div>
        </div>
      ),
    },
    {
      title: "学生情况",
      key: "students",
      render: (record: Course) => (
        <div>
          <div style={{ fontSize: '14px', fontWeight: 'bold' }}>
            {record.totalStudents}人
          </div>
          <div style={{ fontSize: '11px', color: '#666' }}>
            {record.totalClasses}个班级
          </div>
          <Progress 
            percent={Math.round((record.totalStudents / (record.totalStudents + 20)) * 100)} 
            size="small" 
            style={{ marginTop: 4 }}
          />
        </div>
      ),
    },
    {
      title: "完成率",
      key: "completionRate",
      render: (record: Course) => (
        <div>
          <div style={{ fontSize: '14px', fontWeight: 'bold', color: '#52c41a' }}>
            {record.completionRate}%
          </div>
          <Progress 
            percent={record.completionRate} 
            size="small" 
            strokeColor="#52c41a"
            style={{ marginTop: 4 }}
          />
        </div>
      ),
    },
    {
      title: "平均分",
      key: "averageScore",
      render: (record: Course) => (
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: '16px', fontWeight: 'bold', color: '#1890ff' }}>
            {record.averageScore}
          </div>
          <div style={{ fontSize: '11px', color: '#666' }}>分</div>
        </div>
      ),
    },
    {
      title: "操作",
      key: "actions",
      render: (record: Course) => (
        <Space size="small">
            <Button 
            type="link" 
            size="small" 
              icon={<EyeOutlined />} 
              onClick={() => {
                setSelectedCourse(record);
                setCourseDetailVisible(true);
              }}
          >
            查看
          </Button>
          <Button 
            type="link" 
            size="small" 
            icon={<EditOutlined />}
            onClick={() => navigate(`/teacher/courses/${record.id}/edit`)}
          >
            编辑
          </Button>
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item key="students" icon={<TeamOutlined />} onClick={() => {
                  setSelectedCourseForStudents(record);
                  setStudentSearchText("");
                  setStudentStatusFilter("all");
                  setStudentMajorFilter("all");
                }}>
                  学生管理
                </Menu.Item>
                <Menu.Item key="classes" icon={<BookOutlined />} onClick={() => {
                  setSelectedCourse(record);
                  setClassDetailVisible(true);
                }}>
                  班级详情
                </Menu.Item>
                <Menu.Item key="homework" icon={<FileTextOutlined />} onClick={() => {
                  setSelectedCourseForHomework(record);
                  homeworkForm.resetFields();
                  setPublishHomeworkModalVisible(true);
                }}>
                  发布作业
                </Menu.Item>
                <Menu.Item key="exam" icon={<ExperimentOutlined />} onClick={() => {
                  navigate("/teacher/exam-generation", { 
                    state: { 
                      courseId: record.id, 
                      courseName: record.name,
                      type: "exam"
                    } 
                  });
                }}>
                  智能出题(考试)
                </Menu.Item>
                <Menu.Item key="export" icon={<ExportOutlined />} onClick={handleExportData}>
                  导出数据
                </Menu.Item>
                <Menu.Divider />
                <Menu.Item key="delete" icon={<DeleteOutlined />} danger onClick={() => handleDeleteCourse(record.id)}>
                  删除课程
                </Menu.Item>
              </Menu>
            }
            trigger={['click']}
          >
            <Button type="link" size="small" icon={<MoreOutlined />} />
          </Dropdown>
        </Space>
      ),
    },
  ];

  const navigateToAdd = () => {
    navigate("/teacher/courses/add");
  };

  const showClassDetail = (classInfo: Class) => {
    setSelectedClass(classInfo);
    setClassDetailVisible(true);
  };

  const handleDeleteCourse = (courseId: string) => {
    message.success("课程删除成功");
  };

  const handleExportData = () => {
    message.success("数据导出成功");
  };

  const handleImportData = () => {
    message.success("数据导入成功");
  };

  const handleAdvancedSearch = () => {
    setShowAdvancedSearch(!showAdvancedSearch);
  };

  const handleResetAll = () => {
    setSearchText("");
    setStatusFilter("all");
    setDifficultyFilter("all");
    setCategoryFilter("all");
    setCreateTimeFilter("");
    setRatingFilter("");
    setCompletionRateFilter("");
    message.success("筛选条件已重置");
  };

  const handleAddStudent = () => {
    if (!newStudentData.name || !newStudentData.studentId || !newStudentData.major || !newStudentData.grade) {
      message.error("请填写完整的学生信息");
      return;
    }
      message.success("学生添加成功");
      setAddStudentModalVisible(false);
      setNewStudentData({ name: "", studentId: "", major: "", grade: "", email: "" });
  };

  const handleRemoveStudent = (studentId: string, courseId: string) => {
        message.success("学生移除成功");
  };

  const handleViewStudentDetail = (student: Student) => {
    Modal.info({
      title: "学生详情",
      content: (
        <Descriptions column={1} size="small">
          <Descriptions.Item label="姓名">{student.name}</Descriptions.Item>
          <Descriptions.Item label="学号">{student.studentId}</Descriptions.Item>
          <Descriptions.Item label="专业">{student.major}</Descriptions.Item>
          <Descriptions.Item label="年级">{student.grade}</Descriptions.Item>
          <Descriptions.Item label="出勤率">{student.attendance}%</Descriptions.Item>
          <Descriptions.Item label="成绩">{student.score}分</Descriptions.Item>
        </Descriptions>
      ),
    });
  };

  // 发布作业处理函数
  const handlePublishHomework = () => {
    homeworkForm.validateFields().then(values => {
      if (selectedCourseForHomework) {
        // 模拟发布作业
        message.loading("正在发布作业...", 2).then(() => {
          message.success(`作业"${values.title}"发布成功！`);
          setPublishHomeworkModalVisible(false);
          homeworkForm.resetFields();
          
          // 跳转到作业批改界面
          navigate("/teacher/homework-grading", {
            state: {
              courseId: selectedCourseForHomework.id,
              courseName: selectedCourseForHomework.name,
              homeworkTitle: values.title
            }
          });
        });
      }
    });
  };

  return (
    <div style={{ padding: '24px' }}>
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={4}>
          <Card>
            <Statistic
              title="总课程数"
              value={stats.totalCourses}
              prefix={<BookOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="总学生数"
              value={stats.totalStudents}
              prefix={<TeamOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="总班级数"
              value={stats.totalClasses}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="进行中课程"
              value={stats.activeCourses}
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="热门课程"
              value={stats.popularCourses}
              prefix={<StarOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="平均评分"
              value={stats.averageRating.toFixed(1)}
              prefix={<TrophyOutlined />}
              valueStyle={{ color: '#722ed1' }}
              suffix="分"
            />
          </Card>
        </Col>
      </Row>

      {/* 搜索和筛选 */}
      <Card style={{ marginBottom: '24px' }}>
        <Row gutter={16} align="middle">
          <Col span={6}>
            <Input
              placeholder="搜索课程名称、代码或描述"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
            />
          </Col>
          <Col span={3}>
            <Select
              placeholder="状态"
              value={statusFilter}
              onChange={setStatusFilter}
              style={{ width: '100%' }}
            >
              <Select.Option value="all">全部状态</Select.Option>
              <Select.Option value="进行中">进行中</Select.Option>
              <Select.Option value="未开始">未开始</Select.Option>
              <Select.Option value="已结束">已结束</Select.Option>
            </Select>
          </Col>
          <Col span={3}>
            <Select
              placeholder="难度"
              value={difficultyFilter}
              onChange={setDifficultyFilter}
              style={{ width: '100%' }}
            >
              <Select.Option value="all">全部难度</Select.Option>
              <Select.Option value="简单">简单</Select.Option>
              <Select.Option value="中等">中等</Select.Option>
              <Select.Option value="困难">困难</Select.Option>
            </Select>
          </Col>
          <Col span={3}>
            <Select
              placeholder="类别"
              value={categoryFilter}
              onChange={setCategoryFilter}
              style={{ width: '100%' }}
            >
              <Select.Option value="all">全部类别</Select.Option>
              <Select.Option value="必修">必修</Select.Option>
              <Select.Option value="选修">选修</Select.Option>
              <Select.Option value="实验">实验</Select.Option>
            </Select>
          </Col>
          <Col span={3}>
              <Button 
                icon={<FilterOutlined />} 
              onClick={handleAdvancedSearch}
              type={showAdvancedSearch ? "primary" : "default"}
              >
                高级筛选
              </Button>
          </Col>
          <Col span={3}>
            <Button icon={<ReloadOutlined />} onClick={handleResetAll}>
                重置
              </Button>
          </Col>
          <Col span={3}>
            <Button type="primary" icon={<PlusOutlined />} onClick={navigateToAdd}>
              新建课程
            </Button>
          </Col>
        </Row>
        
        {/* 高级筛选 */}
        {showAdvancedSearch && (
          <Row gutter={16} style={{ marginTop: '16px' }}>
            <Col span={6}>
              <DatePicker 
                placeholder="创建时间" 
                style={{ width: '100%' }}
                onChange={(date, dateString) => setCreateTimeFilter(dateString as string)}
              />
            </Col>
            <Col span={6}>
              <Select
                placeholder="评分范围"
                value={ratingFilter}
                onChange={setRatingFilter}
                style={{ width: '100%' }}
              >
                <Select.Option value="">全部评分</Select.Option>
                <Select.Option value="4.5-5.0">4.5-5.0分</Select.Option>
                <Select.Option value="4.0-4.5">4.0-4.5分</Select.Option>
                <Select.Option value="3.5-4.0">3.5-4.0分</Select.Option>
                <Select.Option value="3.0-3.5">3.0-3.5分</Select.Option>
              </Select>
            </Col>
            <Col span={6}>
              <Select
                placeholder="完成率范围"
                value={completionRateFilter}
                onChange={setCompletionRateFilter}
                style={{ width: '100%' }}
              >
                <Select.Option value="">全部完成率</Select.Option>
                <Select.Option value="90-100">90-100%</Select.Option>
                <Select.Option value="80-90">80-90%</Select.Option>
                <Select.Option value="70-80">70-80%</Select.Option>
                <Select.Option value="60-70">60-70%</Select.Option>
              </Select>
            </Col>
            <Col span={6}>
          <Space>
            <Button icon={<ImportOutlined />} onClick={handleImportData}>
                  导入
            </Button>
            <Button icon={<ExportOutlined />} onClick={handleExportData}>
                  导出
          </Button>
          </Space>
            </Col>
          </Row>
        )}
      </Card>

      {/* 课程列表 */}
      <Card>
        <Table
          columns={columns}
              dataSource={filteredCourses}
          rowKey="id"
          pagination={{
                total: filteredCourses.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      </Card>

      {/* 课程详情弹窗 */}
      <Modal
        title="课程详情"
        visible={courseDetailVisible}
        onCancel={() => setCourseDetailVisible(false)}
        footer={null}
        width={800}
      >
        {selectedCourse && (
          <div>
            <Descriptions column={2} bordered>
              <Descriptions.Item label="课程名称">{selectedCourse.name}</Descriptions.Item>
              <Descriptions.Item label="课程代码">{selectedCourse.code}</Descriptions.Item>
              <Descriptions.Item label="学分">{selectedCourse.credit}</Descriptions.Item>
              <Descriptions.Item label="学期">{selectedCourse.semester}</Descriptions.Item>
              <Descriptions.Item label="授课教师">{selectedCourse.teacher}</Descriptions.Item>
              <Descriptions.Item label="课程状态">
                <Tag color={selectedCourse.status === "进行中" ? "green" : "blue"}>
                  {selectedCourse.status}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="上课时间">{selectedCourse.schedule}</Descriptions.Item>
              <Descriptions.Item label="上课地点">{selectedCourse.location}</Descriptions.Item>
              <Descriptions.Item label="学生总数">{selectedCourse.totalStudents}人</Descriptions.Item>
              <Descriptions.Item label="班级数量">{selectedCourse.totalClasses}个</Descriptions.Item>
              <Descriptions.Item label="课程评分">{selectedCourse.rating.toFixed(1)}分</Descriptions.Item>
              <Descriptions.Item label="完成率">{selectedCourse.completionRate}%</Descriptions.Item>
              <Descriptions.Item label="平均分">{selectedCourse.averageScore}分</Descriptions.Item>
              <Descriptions.Item label="创建时间">{selectedCourse.createTime}</Descriptions.Item>
            </Descriptions>
            
            <Divider />
            
            <Title level={4}>课程描述</Title>
            <Text>{selectedCourse.description}</Text>
            
            <Divider />
            
            <Title level={4}>班级列表</Title>
            <List
              dataSource={selectedCourse.classes}
              renderItem={(cls) => (
                <List.Item
                  actions={[
                    <Button type="link" onClick={() => showClassDetail(cls)}>
                      查看详情
                    </Button>
                  ]}
                >
                  <List.Item.Meta
                    title={cls.name}
                    description={`${cls.enrolled}/${cls.capacity}人 · ${cls.schedule} · ${cls.location}`}
                  />
                </List.Item>
              )}
            />
          </div>
        )}
      </Modal>

      {/* 班级详情弹窗 */}
      <Modal
        title="班级详情"
        visible={classDetailVisible}
        onCancel={() => setClassDetailVisible(false)}
        footer={null}
        width={1000}
      >
        {selectedClass && (
          <div>
            <Descriptions column={3} bordered style={{ marginBottom: 16 }}>
              <Descriptions.Item label="班级名称">{selectedClass.name}</Descriptions.Item>
              <Descriptions.Item label="学生数量">{selectedClass.enrolled}/{selectedClass.capacity}</Descriptions.Item>
              <Descriptions.Item label="上课时间">{selectedClass.schedule}</Descriptions.Item>
              <Descriptions.Item label="上课地点">{selectedClass.location}</Descriptions.Item>
              <Descriptions.Item label="班级状态">
                <Tag color={selectedClass.status === "active" ? "green" : "blue"}>
                  {selectedClass.status === "active" ? "进行中" : "未开始"}
                </Tag>
              </Descriptions.Item>
            </Descriptions>

            <Table
              columns={[
                {
                  title: "学生信息",
                  key: "studentInfo",
                  render: (student: Student) => (
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <Avatar src={student.avatar} style={{ marginRight: 8 }} />
                      <div>
                        <div style={{ fontWeight: 'bold' }}>{student.name}</div>
                        <div style={{ fontSize: '12px', color: '#666' }}>
                          {student.studentId} · {student.major} · {student.grade}
                        </div>
                      </div>
                    </div>
                  ),
                },
                {
                  title: "出勤率",
                  dataIndex: "attendance",
                  key: "attendance",
                  render: (attendance: number) => (
                    <div>
                      <div style={{ fontWeight: 'bold', color: attendance >= 90 ? '#52c41a' : attendance >= 80 ? '#faad14' : '#f5222d' }}>
                        {attendance}%
                      </div>
                      <Progress percent={attendance} size="small" />
                    </div>
                  ),
                },
                {
                  title: "成绩",
                  dataIndex: "score",
                  key: "score",
                  render: (score: number) => (
                    <div style={{ textAlign: 'center' }}>
                      <div style={{ fontSize: '16px', fontWeight: 'bold', color: score >= 90 ? '#52c41a' : score >= 80 ? '#faad14' : score >= 70 ? '#1890ff' : '#f5222d' }}>
                        {score}
                      </div>
                      <div style={{ fontSize: '11px', color: '#666' }}>分</div>
                    </div>
                  ),
                },
                {
                  title: "操作",
                  key: "actions",
                  render: (student: Student) => (
                    <Space>
                      <Button type="link" size="small" onClick={() => handleViewStudentDetail(student)}>
                        详情
                      </Button>
                      <Popconfirm
                        title="确定要移除此学生吗？"
                        onConfirm={() => handleRemoveStudent(student.id, selectedClass.courseId)}
                      >
                        <Button type="link" size="small" danger>
                          移除
                        </Button>
                      </Popconfirm>
                    </Space>
                  ),
                },
              ]}
              dataSource={selectedClass.students}
              rowKey="id"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
              }}
            />
          </div>
        )}
      </Modal>

      {/* 添加学生弹窗 */}
      <Modal
        title="添加学生"
        visible={addStudentModalVisible}
        onOk={handleAddStudent}
        onCancel={() => setAddStudentModalVisible(false)}
      >
        <Form layout="vertical">
          <Form.Item label="姓名" required>
            <Input
              value={newStudentData.name}
              onChange={(e) => setNewStudentData({ ...newStudentData, name: e.target.value })}
              placeholder="请输入学生姓名"
            />
          </Form.Item>
          <Form.Item label="学号" required>
            <Input
              value={newStudentData.studentId}
              onChange={(e) => setNewStudentData({ ...newStudentData, studentId: e.target.value })}
              placeholder="请输入学号"
            />
          </Form.Item>
          <Form.Item label="专业" required>
            <Input
              value={newStudentData.major}
              onChange={(e) => setNewStudentData({ ...newStudentData, major: e.target.value })}
              placeholder="请输入专业"
            />
          </Form.Item>
          <Form.Item label="年级" required>
            <Input
              value={newStudentData.grade}
              onChange={(e) => setNewStudentData({ ...newStudentData, grade: e.target.value })}
              placeholder="请输入年级"
            />
          </Form.Item>
          <Form.Item label="邮箱">
            <Input
              value={newStudentData.email}
              onChange={(e) => setNewStudentData({ ...newStudentData, email: e.target.value })}
              placeholder="请输入邮箱"
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 发布作业弹窗 */}
      <Modal
        title="发布作业"
        visible={publishHomeworkModalVisible}
        onOk={handlePublishHomework}
        onCancel={() => {
          setPublishHomeworkModalVisible(false);
          homeworkForm.resetFields();
        }}
        width={600}
      >
        <Form form={homeworkForm} layout="vertical">
          <Form.Item label="课程名称">
            <Input 
              value={selectedCourseForHomework?.name} 
              disabled 
              style={{ backgroundColor: '#f5f5f5' }}
            />
          </Form.Item>
          <Form.Item 
            name="title" 
            label="作业标题" 
            rules={[{ required: true, message: "请输入作业标题" }]}
          >
            <Input placeholder="请输入作业标题" />
          </Form.Item>
          <Form.Item 
            name="description" 
            label="作业描述" 
            rules={[{ required: true, message: "请输入作业描述" }]}
          >
            <TextArea rows={4} placeholder="请输入作业描述和要求" />
          </Form.Item>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item 
                name="dueDate" 
                label="截止日期" 
                rules={[{ required: true, message: "请选择截止日期" }]}
              >
                <DatePicker 
                  style={{ width: '100%' }} 
                  placeholder="请选择截止日期"
                  showTime={{ format: 'HH:mm' }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item 
                name="totalScore" 
                label="总分" 
                rules={[{ required: true, message: "请输入总分" }]}
              >
                <InputNumber 
                  min={1} 
                  max={100} 
                  style={{ width: '100%' }} 
                  placeholder="请输入总分" 
                />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item 
            name="type" 
            label="作业类型" 
            rules={[{ required: true, message: "请选择作业类型" }]}
          >
            <Select placeholder="请选择作业类型">
              <Option value="manual">手动出题</Option>
              <Option value="ai">AI智能出题</Option>
            </Select>
          </Form.Item>
          <Form.Item 
            name="allowLate" 
            label="允许逾期提交"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default TeacherCourses;
